#!/usr/bin/python
#-*- coding: utf-8 -*-


import db
import sys
import hashlib

reload(sys)
sys.setdefaultencoding('utf8')

class User(object):
    """docstring for User"""
    def __init__(self):
        try:
            db_object = db.db_object()
            self.conn,self.cur = db_object
        except Exception, e:
            raise e

    #auth
    def auth(self,phone,passwd):
        passwd = hashlib.md5(passwd).hexdigest()
        query = '''
                SELECT phone,nickname,passwd,status
                FROM user
                WHERE phone = {phone}
                '''.format(phone=phone)
        try:
            if not self.cur.execute(query):#check phone
                return {
                    'code':3,
                    'message':'Auth fail,User does not exist'
                }
            phone,nickname,db_passwd,status = self.cur.fetchone()
            if not status:#check status
                return {
                        'code':2,
                        'message':'Auth fail,The user does not activate'
                    }

            if not passwd == db_passwd:#check pass
                return {
                        'code':1,
                        'message':'Auth fail,Wrong password'
                    }
            else:
                return {
                        'code':0,
                        'message':'Auth ok',
                        'data':[phone,nickname]
                    }
        except Exception, e:
            raise e

    def reg(self,phone,passwd,nickname,class_type,class_id):
        passwd = hashlib.md5(passwd).hexdigest()
        query = '''
                SELECT phone
                FROM user
                WHERE phone = '{phone}'
                '''.format(phone=phone)
        try:
            if self.cur.execute(query):#check phone
                return {
                    'code':50,
                    'message':'user User exists, Please Replace username'
                }
            query = '''
                    INSERT INTO user(phone,passwd,nickname,class_typeid,class_id)
                    VALUES('{phone}','{passwd}','{nickname}',(SELECT
                                                                id
                                                            FROM
                                                                class_type
                                                            WHERE
                                                                class_type_info = '{class_type}'),'{class_id}')
                    '''.format(phone=phone,passwd=passwd,nickname=nickname,class_type=class_type,class_id=class_id)
            try:
                if self.cur.execute(query):
                    self.conn.commit();self.cur.close();self.conn.close()
                    return {
                        'code':0,
                        'message':'reg success'
                    }
                else:
                    return {
                        'code':51,
                        'message':'reg fail,please you accout sysadmin'
                    }
            except Exception, e:
                raise e
        except Exception, e:
            raise e

    def fetch_user(self,class_type=None,class_id=None):
        result = {
            'code':0,
            'message':'success'
        }
        if not class_type:
            query = '''
                    SELECT
                        user.id,
                        user.phone,
                        user.nickname,
                        class_type.class_type_info,
                        class.class_info
                    FROM
                        user,
                        class_type,
                        class
                    WHERE
                        user.class_typeid = class_type.id AND
                        user.class_id = class.id
                    '''
        else:
            if class_id:
                query = '''
                        SELECT
                            id,
                            phone,
                            nickname
                        FROM
                            user
                        WHERE
                            class_typeid = (
                                SELECT
                                    id
                                FROM
                                    class_type
                                WHERE
                                    class_type_info = '{class_type}'
                            )
                        AND class_id = {class_id}
                        '''.format(class_type=class_type,
                                   class_id=class_id)
            else:
                query = '''
                        SELECT
                            id,
                            phone,
                            nickname
                        FROM
                            user
                        WHERE
                            class_typeid = (
                                SELECT
                                    id
                                FROM
                                    class_type
                                WHERE
                                    class_type_info = '{class_type}'
                            )
                        '''.format(class_type=class_type)
        try:
            self.cur.execute(query)
            data = self.cur.fetchall()

            result['data'] = data
            return result
        except Exception,e:
            result['code'] = 200,
            result['message'] = 'db error',e
            return result

    def fetch_class_type(self):
        result = {
            'code':0,
            'message':'success'
        }
        query = 'SELECT class_type_info FROM class_type'
        try:
            self.cur.execute(query)
            data = self.cur.fetchall()
            result['data'] = data
            return result
        except Exception,e:
            result['code'] = 200,
            result['message'] = 'db error',e
            return result

    def fetch_class_id(self):
        result = {
            'code':0,
            'message':'success'
        }
        query = 'SELECT id FROM class'
        try:
            self.cur.execute(query)
            data = self.cur.fetchall()
            result['data'] = data
            return result
        except Exception,e:
            result['code'] = 200,
            result['message'] = 'db error',e
            return result

if __name__ == '__main__':
    u = User()
    #print u.auth(phone='15010220814',passwd='zuoloveyou')
    #print u.reg(phone='15010220816',passwd='zuoloveyu',nickname='茶总')
    #print u.fetch_user(class_type='linux',class_id=2)


